'use client';

import { useEffect, useState } from 'react';
import { Card, Typography, Descriptions, Button, Message, Spin, Steps, Result } from '@arco-design/web-react';
import { useRouter, useSearchParams } from 'next/navigation';
import { useAuth } from '@/contexts/AuthContext';
import { bookingApi, checkInApi, roomApi, customerApi } from '@/services/api';
import { Booking } from '@/types';

const { Title, Text } = Typography;
const Step = Steps.Step;

export default function CheckInPage() {
  const [booking, setBooking] = useState<Booking | null>(null);
  const [loading, setLoading] = useState(true);
  const [actionLoading, setActionLoading] = useState(false);
  const [currentStep, setCurrentStep] = useState(0);
  const [success, setSuccess] = useState(false);

  const router = useRouter();
  const searchParams = useSearchParams();
  const bookingId = searchParams.get('bookingId');

  console.log('CheckInPage 渲染 - bookingId:', bookingId);

  const { userType, isAuthenticated } = useAuth();

  useEffect(() => {
    console.log('CheckInPage useEffect 执行', { isAuthenticated, userType, bookingId, searchParams: searchParams.toString() });

    // 如果未登录或不是管理员，重定向到登录页
    if (!isAuthenticated) {
      router.push('/admin/login');
      return;
    }

    if (userType !== 'admin') {
      router.push('/');
      return;
    }

    // 如果没有预订ID，重定向到预订管理页面
    if (!bookingId) {
      console.log('bookingId 为空，重定向到预订管理');
      router.push('/admin/bookings');
      return;
    }

    // 只有当 bookingId 可用时才 fetch 数据
    if (bookingId) {
      fetchBookingData();
    }

    // 添加 searchParams 到依赖数组，确保参数变化时触发
  }, [isAuthenticated, userType, bookingId, router, searchParams]);

  const fetchBookingData = async () => {
    setLoading(true);
    console.log('开始获取预订数据，预订ID:', bookingId);
    try {
      const response = await bookingApi.getById(parseInt(bookingId!));
      console.log('获取预订数据响应:', response);

      // 修改：成功获取预订信息后，并行获取房间和客户信息
      if (response.code === 200 && response.data) {
        // 兼容类型：将 customerId 映射为 customerID
        const bookingData = {
          ...response.data,
          customerID: (response.data as any).customerId,
        };

        // 并行发起房间和客户信息请求
        const [roomResponse, customerResponse] = await Promise.all([
          roomApi.getById(bookingData.roomId), // 获取房间信息
          customerApi.getById(bookingData.customerID) // 统一用 customerID
        ]);

        let roomInfo = undefined;
        if (roomResponse.code === 200 && roomResponse.data) {
          roomInfo = roomResponse.data;
        } else {
          console.error(`获取房间信息失败，预订ID: ${bookingData.bookingId}`, roomResponse);
        }

        let customerInfo = undefined;
        if (customerResponse.code === 200 && customerResponse.data) {
          customerInfo = customerResponse.data;
        } else {
          console.error(`获取客户信息失败，预订ID: ${bookingData.bookingId}`, customerResponse);
        }

        // 将获取到的详细信息合并到预订数据中
        const fullBookingData = {
          ...bookingData,
          roomInfo, // 添加房间信息
          customerInfo // 添加客户信息
        };

        setBooking(fullBookingData as Booking); // 更新状态

        // 设置当前步骤
        if (fullBookingData.status === '预订中') {
          setCurrentStep(1); // 待入住
        } else if (fullBookingData.status === '已入住') {
          setCurrentStep(2); // 已入住，待退房
        } else if (fullBookingData.status === '已退房') {
          setCurrentStep(3); // 已完成
        }

      } else {
        // Message.error(response.message || '获取预订信息失败'); // 临时注释掉
        console.error('获取预订信息失败响应:', response);
        router.push('/admin/bookings');
      }
    } catch (error) {
      console.error('获取预订信息错误:', error);
      // Message.error('获取预订信息时发生错误'); // 临时注释掉
      router.push('/admin/bookings');
    } finally {
      setLoading(false);
    }
  };

  const handleCheckIn = async () => {
    if (!booking) return;

    setActionLoading(true);
    try {
      const response = await checkInApi.checkIn(booking.bookingId!);
      if (response.code === 200) {
        Message.success('入住办理成功');
        setSuccess(true);
        // 刷新预订数据
        fetchBookingData();
      } else {
        // Message.error(response.message || '入住办理失败'); // 临时注释掉
        console.error('入住办理失败响应:', response);
      }
    } catch (error) {
      console.error('入住办理错误:', error);
      // Message.error('入住办理时发生错误'); // 临时注释掉
    } finally {
      setActionLoading(false);
    }
  };

  const handleCheckOut = async () => {
    if (!booking) return;

    setActionLoading(true);
    try {
      const response = await checkInApi.checkOut(booking.bookingId!);
      if (response.code === 200) {
        Message.success('退房办理成功');
        setSuccess(true);
        // 刷新预订数据
        fetchBookingData();
      } else {
        // Message.error(response.message || '退房办理失败'); // 临时注释掉
        console.error('退房办理失败响应:', response);
      }
    } catch (error) {
      console.error('退房办理错误:', error);
      // Message.error('退房办理时发生错误'); // 临时注释掉
    } finally {
      setActionLoading(false);
    }
  };

  if (loading) {
    return (
      <div className="flex justify-center items-center min-h-[60vh]">
        <Spin />
      </div>
    );
  }

  if (!booking) {
    return null;
  }

  return (
    <div className="max-w-3xl mx-auto py-8">
      <Card className="shadow-md">
        <div className="mb-6">
          <Title heading={3}>{currentStep === 1 ? '办理入住' : currentStep === 2 ? '办理退房' : '预订详情'}</Title>
          <Text type="secondary">预订ID: {booking.bookingId}</Text>
        </div>

        <Steps current={currentStep} className="mb-8">
          <Step title="已预订" description="客户已完成预订" />
          <Step title="待入住" description="等待客户入住" />
          <Step title="已入住" description="客户入住中" />
          <Step title="已完成" description="预订已完成" />
        </Steps>

        {success && (
          <Result
            status="success"
            title={currentStep === 2 ? "入住办理成功！" : currentStep === 3 ? "退房办理成功！" : "操作成功！"}
            className="mb-6"
          />
        )}

        <div className="mb-6">
          <Title heading={5}>预订信息</Title>
          <Descriptions
            column={2}
            data={[
              {
                label: '客户姓名',
                // 修改：从合并后的 customerInfo 中获取姓名或用户名
                value: booking.customerInfo?.name || booking.customerInfo?.username || '-'
              },
              {
                label: '房间号',
                // 修改：从合并后的 roomInfo 中获取房间号
                value: booking.roomInfo?.roomNumber || '-'
              },
              {
                label: '房间类型',
                // 修改：从合并后的 roomInfo 中获取房间类型
                value: booking.roomInfo?.roomType || '-'
              },
              {
                label: '预订状态',
                value: booking.status
              },
              {
                label: '入住日期',
                value: new Date(booking.checkInTime).toLocaleDateString()
              },
              {
                label: '退房日期',
                value: new Date(booking.checkOutTime).toLocaleDateString()
              },
              {
                label: '总金额',
                value: `¥${booking.totalAmount}`
              }
            ]}
            labelStyle={{ fontWeight: 'bold' }}
          />
        </div>

        <div className="flex justify-center space-x-4">
          {currentStep === 1 && (
            <Button
              type="primary"
              loading={actionLoading}
              onClick={handleCheckIn}
              size="large"
            >
              办理入住
            </Button>
          )}

          {currentStep === 2 && (
            <Button
              type="primary"
              status="success"
              loading={actionLoading}
              onClick={handleCheckOut}
              size="large"
            >
              办理退房
            </Button>
          )}

          <Button
            type="secondary"
            onClick={() => router.push('/admin/bookings')}
            size="large"
          >
            返回预订列表
          </Button>
        </div>
      </Card>
    </div>
  );
}